package com.ncs.cns.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.ncs.cns.R;
import com.ncs.cns.business.constants.BundleConstants;
import com.ncs.cns.business.to.Event;
import com.ncs.cns.business.to.Resource;
import com.ncs.cns.business.to.TransferObject;
import com.ncs.cns.business.to.UserNcs;
import com.ncs.cns.business.util.DateUtil;
import com.ncs.cns.business.util.JsonConvertor;
import com.ncs.cns.framework.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;


public class CircuseeDetailActivity extends BaseActivity implements OnItemClickListener {
	private Context context;
	private List<String> photoPaths;
	private String eventDetail;
	private String eventSubject;
	private String createdTime;
	private String userName;
	private int watchedNumber;
	private GridView gv;
	private ImageAdapter ia;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private int imgWidth;
	private int screenWidth;
	private int currentEventId;
	private Event currentEvent;	
	//private TextView watchedNumberTv;
	private TextView goodTv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_circusee_detail);		
		context = this.getApplicationContext();	
		init();		
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	        	Intent intent = new Intent();
	    		Bundle b = new Bundle();	
	    		b.putInt(BundleConstants.BUNDLE_EVENT_WATCHED, currentEvent.getEventNumberWatched());
	    		b.putInt(BundleConstants.BUNDLE_EVENT_GOOD, currentEvent.getEventNumberGood());
	    		b.putString(BundleConstants.BUNDLE_EVENT_ISPRAISE, currentEvent.getIsPraise());
	    		intent.putExtras(b);
	    		setResult(RESULT_OK,intent);
	    		finish();
	    		return true;
	        }	        
		return super.onKeyDown(keyCode, event);
	}

	private void init() {
		final Bundle bundle = this.getIntent().getExtras();
		currentEventId = bundle.getInt(BundleConstants.BUNDLE_EVENT_ID);
		currentEvent = eventService.getEvent(currentEventId);
		WatchNumberTask eventTask  = new WatchNumberTask();
		eventTask.execute();
		
		ImageView goodImg = (ImageView) this.findViewById(R.id.good_img);
		if(currentEvent.getIsPraise().equals(Constant.EVENT_Y)){
			goodImg.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), R.drawable.isgood));
		}
		
		long createdMinute = bundle.getLong(BundleConstants.BUNDLE_EVENT_CREATE_MINUTE);
		eventDetail = bundle.getString(BundleConstants.BUNDLE_EVENT_DETAIL);
		eventSubject = bundle.getString(BundleConstants.BUNDLE_EVENT_SUBJECT);		
		createdTime = DateUtil.formatDate(new Date(createdMinute),DateUtil.yyyy_MM_dd_HH_mm_ss);
		userName = bundle.getString(BundleConstants.BUNDLE_EVENT_CREATE_BY);		
		photoPaths = getPhotoList(bundle.getInt(BundleConstants.BUNDLE_EVENT_ID));	
		watchedNumber = bundle.getInt(BundleConstants.BUNDLE_EVENT_WATCHED);
		
		TextView eventSubjectTv = (TextView) this.findViewById(R.id.text_event_sub);
		TextView eventDetailTv = (TextView) this.findViewById(R.id.text_event_detail);
		TextView createdTimeTv = (TextView) this.findViewById(R.id.text_event_created_time);
		TextView userNameTv = (TextView) this.findViewById(R.id.text_event_created_by);
		//watchedNumberTv = (TextView) this.findViewById(R.id.text_event_watched);
		goodTv = (TextView) this.findViewById(R.id.text_event_good);
		goodTv.setText(""+currentEvent.getEventNumberGood());
		//watchedNumberTv.setText(""+watchedNumber);
		eventSubjectTv.setText(eventSubject);
		eventDetailTv.setText(eventDetail);
		createdTimeTv.setText(createdTime);
		userNameTv.setText(userName);		
		
		gv = (GridView) this.findViewById(R.id.imgsList);
		ia = new ImageAdapter();
		gv.setOnItemClickListener(this);
		gv.setAdapter(ia);
		
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.ic_stub)		
		.showImageForEmptyUri(R.drawable.ic_empty)	
		.showImageOnFail(R.drawable.ic_error)		
		.cacheInMemory(true)						
		.cacheOnDisc(true)
		.displayer(new RoundedBitmapDisplayer(20))
		.build();	
		
		DisplayMetrics dm = context.getResources().getDisplayMetrics();
		screenWidth = dm.widthPixels;
		imgWidth = screenWidth/4;
	}

	private List<String> getPhotoList(int eventId) {		
		List<Resource> resources = resourceService.findByEventId(eventId);
		int size = resources.size();
		photoPaths = new ArrayList<String>();	
		if(size>0){								
			for(int i = 0;i < size;i++){
				Resource rec = resources.get(i);
				photoPaths.add(rec.getResourceLocation());						
			}
		}
		return photoPaths;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
		if(view instanceof ImageView){
			Bundle bundle = new Bundle();
			Intent intent = new Intent(context,ImagePagerActivity.class);
			bundle.putInt("index", position);
			bundle.putStringArrayList("paths",(ArrayList)photoPaths);
			bundle.putBoolean(Constant.IS_SHOW_REMOVE_IMG_BUTTON, false);
			intent.putExtras(bundle);
			startActivityForResult(intent, 3);
		}
	}
	
	class ImageAdapter extends BaseAdapter{
		private LayoutInflater inflater;
		public ImageAdapter() {
			inflater = LayoutInflater.from(context);
		}
		@Override
		public int getCount() {
			return photoPaths.size();
		}

		@Override
		public Object getItem(int position) {
			return photoPaths.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView iv = null;
			String path ="";
			if(photoPaths.get(position).startsWith("http")){
				path = photoPaths.get(position);
			}
			else{
				path = Constant.FILE_PREFIX+photoPaths.get(position);
			}
			if(photoPaths.size() == 1){
				if(convertView == null){
					iv = new ImageView(context);
					iv.setLayoutParams(new LayoutParams((screenWidth/3)*2,(screenWidth/3)*2));	
					iv.setAdjustViewBounds(true);	
					iv.setScaleType(ImageView.ScaleType.FIT_XY);					
				}
				else
					iv = (ImageView) convertView;
			}else{
				if(convertView == null){
					iv = new ImageView(context);
					iv.setLayoutParams(new LayoutParams(imgWidth,imgWidth));
					iv.setAdjustViewBounds(true);
					iv.setScaleType(ImageView.ScaleType.FIT_XY);	
				}else
					iv = (ImageView) convertView;
			}
			imageLoader.displayImage(path, iv, options);
			return iv;
		}		
	}
	
	class WatchNumberTask extends AsyncTask<Integer, String, String>{
		@Override
		protected String doInBackground(Integer... params) {
			Map data = new HashMap();		
			if(currentEvent.getIsRead().equals(Constant.EVENT_N)){				
				data.put("isAddWatched", "Y");
				currentEvent.setEventNumberWatched(currentEvent.getEventNumberWatched()+1);
				eventService.updateWatchNumber(currentEvent);
				eventService.updateEventIsReadById(currentEvent.getEventId(), Constant.EVENT_Y);
			}else{
				data.put("isAddWatched", "N");
			}
			
			return executeM005(data);
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(result.equals(""))return;
			Event event = getEventByStr(result);			
			//watchedNumberTv.setText(""+event.getEventNumberWatched()+"");
			currentEvent.setEventNumberWatched(event.getEventNumberWatched());
			currentEvent.setEventNumberGood(event.getEventNumberGood());					
		}
	}
	
	class GoodTask extends AsyncTask<Integer, String, String>{
		@Override
		protected String doInBackground(Integer... params) {
			Map data = new HashMap();
			data.put("good","Y");
			currentEvent.setEventNumberGood(currentEvent.getEventNumberGood()+1);
			currentEvent.setIsPraise(Constant.EVENT_Y);
			eventService.updateEventIsGood(currentEvent.getEventId(),Constant.EVENT_Y);
			eventService.updateGood(currentEvent);
			return executeM005(data);
		}
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(result.equals(""))return;
			Event event = getEventByStr(result);			
			currentEvent.setEventNumberWatched(event.getEventNumberWatched());
			currentEvent.setEventNumberGood(event.getEventNumberGood());			
			goodTv.setText(""+event.getEventNumberGood());			
		}
	}
	
	public void addPraise(View view){
		if(currentEvent.getIsPraise().equals(Constant.EVENT_Y))return;
		ImageView iv = (ImageView) view;
		iv.setImageBitmap(BitmapFactory.decodeResource(context.getResources(),R.drawable.isgood));
		currentEvent.setIsPraise(Constant.EVENT_Y);
		goodTv.setText(Integer.parseInt(goodTv.getText().toString())+1+"");
		GoodTask gt = new GoodTask();
		gt.execute();
	}
	
	private Event getEventByStr(String result){
		JsonConvertor json = JsonConvertor.getInstance();
		TransferObject obj = (TransferObject) json.convert2Object(result, TransferObject.class);
		Event event = obj.getCurrentEvent();
		return event;
	}
	
	private String executeM005(Map data){
		Event event = eventService.getEvent(currentEventId);
		String un = userService.getNameById(currentUserId);				
		TransferObject to = new TransferObject();
		to.setMethodId("M005");
		to.setCurrentEvent(event);
		UserNcs user = new UserNcs();
		user.setUserId(un);
		to.setCurrentUser(user);			
		to.setDataMap(data);
		JsonConvertor json = JsonConvertor.getInstance();
		String objectStr =json.conver2JsonStr(to);
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("dataStr",objectStr));
		String resultStr = httpHelper.doPost(param);
		return resultStr;
	}
	
	public void gotoChat(View view){
		Bundle bundle = new Bundle();
		bundle.putInt(BundleConstants.BUNDLE_EVENT_ID, currentEventId);
		Intent intent = new Intent(this,OldCircuSeeChatActivity.class);
		intent.putExtras(bundle);
		this.startActivity(intent);
	}
}
